import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue'
import {
  Button,
  Checkbox,
  CheckboxGroup,
  DatePicker,
  Form,
  FormItem,
  Image,
  Input,
  message,
  Modal,
  TabPane,
  Tabs,
  Textarea
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'

import qzyApi from '@/apis/qzyApi'
import UploadFile from '@/components/UploadFile'
import { formatDate, isValueEmpty } from '@/utils'

export default defineComponent({
  name: 'QzyPosterManage',
  setup() {
    const visibleJr = ref(false)
    const deleteTitle = ref('')
    const jrTitle = ref('')
    const time = ref('' as any)
    const createVisible = ref(false)
    const visible = ref(false)
    const modalTitle = ref(1)
    //日常图片
    const imgUrl = ref('')
    const imagList = ref([] as any)
    //节日背景图
    const id = ref(0)
    const jrImgList = ref([] as any)
    const jrEditList = ref({} as any)
    const Img = ref('')
    const imgListIndex = ref([] as any)
    const jrImgListIndex = ref([] as any)
    const activeKey = ref(0)
    const arr1 = ref([] as any)
    //节日背景图删除对话框
    function handleDeleteModalJr(item, index) {
      idList.value = []
      deleteTitle.value = item.title
      idList.value.push(item.id)
      visibleJr.value = true
    }
    async function handleDeleteJr() {
      await qzyApi.deleteQzyPoster({ posterIds: idList.value }).then(() => {
        message.success('删除成功')
        visibleJr.value = false
        handleChange()
      })
    }
    //新增或编辑背景图
    async function handleCreate() {
      const param = {
        posterDate: formatDate(time.value as any, 'yyyy-MM-DD'),
        posterTitle: jrTitle.value,
        posterList: [Img.value],
        posterType: 1
      }
      if (modalTitle.value === 1) {
        await qzyApi.addQzyPoster(param).then(async () => {
          jrImgList.value = await qzyApi.findQzyPoster({
            posterType: activeKey.value
          })
          message.success('新增成功')
        })
        createVisible.value = false
      } else {
        jrEditList.value = {
          posterDate: formatDate(time.value as any, 'yyyy-MM-DD'),
          posterTitle: jrTitle.value,
          posterUrl: Img.value,
          id: id.value
        }
        await qzyApi.editQzyPoster(jrEditList.value).then(async () => {
          jrImgList.value = await qzyApi.findQzyPoster({
            posterType: activeKey.value
          })
          message.success('编辑成功')
        })
        createVisible.value = false
      }
    }
    //新增
    function handleCreateModal(flag, item?) {
      modalTitle.value = flag
      createVisible.value = true
      if (item) {
        Img.value = item.posterUrl
        jrTitle.value = item.posterTitle
        time.value = moment(item.posterDate)
        id.value = item.id
      } else {
        Img.value = ''
        jrTitle.value = ''
        time.value = ''
      }
    }

    async function uploadImage(file, code) {
      if (code == 'done') {
        const arr = imgUrl.value.split(',')
        const res = arr.filter(
          item1 => !arr1.value.some(item2 => item2 === item1)
        )
        const newarr = [] as any
        if (res.every(k => k != '')) {
          for (let i = 0; i < res.length; i++) {
            newarr.push(res[i])
          }
          await qzyApi
            .addQzyPoster({
              posterList: res,
              posterType: 0
            })
            .then(async () => {
              imagList.value = await qzyApi.findQzyPoster({
                posterType: activeKey.value
              })
              message.success('上传成功')
              arr1.value = [...arr]
            })
        }
      }
    }
    function checkFile(file) {
      const isImage =
        file.name.toLowerCase().match(/\.(jpeg|jpg|gif|png|webp|bmp)$/) != null
      if (!isImage) {
        message.error('图片格式不正确')
      }
      return isImage
    }
    const idList = ref([] as any)
    //选择图片
    function handleImg(e: any, id, index) {
      if (e.target.checked) {
        idList.value.push(id)
        imgListIndex.value.push(index)
      } else {
        for (let i = 0; i < idList.value.length; i++) {
          if (idList.value[i] === id) {
            idList.value.splice(i, 1)
            imgListIndex.value.splice(i, 1)
          }
        }
      }
    }
    //批量删除图片
    function handleDeleteModal() {
      if (imgListIndex.value.length == 0) {
        message.warn('请选择需要删除的图片')
      } else {
        visible.value = true
      }
    }
    async function handleDelete() {
      imagList.value = imagList.value.filter(
        (k, index) => !imgListIndex.value.includes(index)
      )
      visible.value = false
      await qzyApi.deleteQzyPoster({ posterIds: idList.value }).then(() => {
        message.success('删除成功')
        imgListIndex.value = []
        idList.value = []
      })
      handleChange()
    }
    async function handleChange() {
      const data = await qzyApi.findQzyPoster({ posterType: activeKey.value })
      if (activeKey.value === 0) {
        imagList.value = [...data]
      } else {
        jrImgList.value = [...data]
      }
    }
    onMounted(async () => {
      const data = await qzyApi.findQzyPoster({ posterType: activeKey.value })
      imagList.value = [...data]
    })
    return {
      id,
      idList,
      time,
      deleteTitle,
      jrTitle,
      Img,
      jrImgList,
      imgUrl,
      activeKey,
      imagList,
      visible,
      modalTitle,
      createVisible,
      visibleJr,
      arr1,
      handleDeleteModalJr,
      handleDeleteJr,
      handleCreate,
      uploadImage,
      handleDelete,
      handleCreateModal,
      handleDeleteModal,
      handleImg,
      checkFile,
      handleChange
    }
  },
  render() {
    return (
      <div>
        <Tabs v-model:activeKey={this.activeKey} onChange={this.handleChange}>
          <TabPane key={0} tab="日常背景图">
            <UploadFile
              maxLength={999999}
              v-model={[this.imgUrl, 'urls']}
              listType={'text'}
              onChange={this.uploadImage}
              showUploadList={false}
              beforeUpload={this.checkFile}
            >
              <Button type="primary">上传日常图片</Button>
            </UploadFile>
            <Button
              type="primary"
              style={{ marginLeft: '25px' }}
              onClick={this.handleDeleteModal}
            >
              批量删除
            </Button>
            <span style={{ color: '#aaaaaa' }}>
              （注：如需多选图片，在选择图片时按住Ctrl即可多选）
            </span>
            <div
              style={{
                display: 'flex',
                maxWidth: '100%',
                flexWrap: 'wrap',
                marginBottom: '50px'
              }}
            >
              {this.imagList.map((k, index) => (
                <div
                  style={{
                    marginTop: '20px',
                    width: '230px',
                    height: '370px',
                    border: '1px solid #9c9c9c',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginRight: '30px',
                    position: 'relative'
                  }}
                >
                  <CheckboxGroup>
                    <Checkbox
                      style={{
                        position: 'absolute',
                        right: '1%',
                        top: '0'
                      }}
                      value={k.posterUrl}
                      onChange={(e: Event) => this.handleImg(e, k.id, index)}
                    ></Checkbox>
                  </CheckboxGroup>
                  <Image
                    src={k.posterUrl}
                    style={{
                      width: '185px',
                      height: '335px'
                    }}
                  ></Image>
                </div>
              ))}
            </div>
          </TabPane>
          <TabPane key={1} tab="节日背景图">
            <Button type="primary" onClick={() => this.handleCreateModal(1)}>
              新增节日背景图
            </Button>
            <div
              style={{
                display: 'flex',
                maxWidth: '100%',
                flexWrap: 'wrap',
                marginBottom: '50px'
              }}
            >
              {this.jrImgList.map((k, index) => (
                <div
                  style={{
                    marginTop: '20px',
                    width: '230px',
                    height: '430px',
                    border: '1px solid #9c9c9c',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginRight: '30px',
                    position: 'relative'
                  }}
                >
                  <Image
                    src={k.posterUrl}
                    style={{
                      marginTop: '5px',
                      width: '185px',
                      height: '330px'
                    }}
                  ></Image>
                  <span>主题：{k.posterTitle}</span>
                  <span>生效时间：{k.posterDate}</span>
                  <div
                    style={{
                      marginTop: '7px',
                      width: '100px',
                      display: 'flex',
                      justifyContent: 'space-between'
                    }}
                  >
                    <EditOutlined
                      style={{ fontSize: '20px' }}
                      onClick={() => this.handleCreateModal(2, k)}
                    />
                    <DeleteOutlined
                      style={{ fontSize: '20px' }}
                      onClick={() => this.handleDeleteModalJr(k, index)}
                    />
                  </div>
                </div>
              ))}
            </div>
            <Modal
              v-model:visible={this.createVisible}
              onOk={this.handleCreate}
              title={this.modalTitle == 1 ? '新增' : '编辑'}
              destroyOnClose
              width={500}
            >
              <Form labelCol={{ span: 5 }} preserve={false}>
                <FormItem label="主题" required>
                  <Input
                    style={{ width: '300px' }}
                    v-model:value={this.jrTitle}
                  ></Input>
                </FormItem>
                <FormItem label="生效时间" required>
                  <DatePicker format="YYYY/MM/DD" v-model:value={this.time} />
                </FormItem>
                <FormItem label="主题图片" required>
                  <UploadFile v-model={[this.Img, 'urls']}>上传图片</UploadFile>
                </FormItem>
              </Form>
            </Modal>
          </TabPane>
        </Tabs>
        <Modal
          v-model:visible={this.visible}
          onOk={this.handleDelete}
          width={300}
        >
          确认删除所选择的背景图？
        </Modal>
        <Modal
          v-model:visible={this.visibleJr}
          onOk={this.handleDeleteJr}
          width={300}
        >
          确认删除{this.deleteTitle}的背景图？
        </Modal>
      </div>
    )
  }
})
